package cn.zj.smart.util;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

/**
 * zip压缩解压
 */
public class ZipUtil {
    /**
     * 压缩文件
     * @param zipFileName
     * @param dir
     */
    public static void zip(String zipFileName, String dir) {
        File inputFile = new File(dir);
        try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(
                zipFileName))) {
            zip(out, inputFile, "");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 缓冲器大小
     */
    private static final int BUFFER = 512;

    private static void zip(ZipOutputStream out, File f, String base) {
        try {
            if (f.isDirectory()) {
                File[] fl = f.listFiles();
                for (File file : fl) {
                    zip(out, file, file.getName());
                }
            } else {
                ZipEntry zipEntry = new ZipEntry(base);
                zipEntry.setSize(f.length());
                zipEntry.setTime(f.lastModified());
                out.putNextEntry(zipEntry);
                int readLength;
                byte[] buffer = new byte[BUFFER];
                InputStream is = new BufferedInputStream(new FileInputStream(f));

                while ((readLength = is.read(buffer, 0, BUFFER)) != -1) {
                    out.write(buffer, 0, readLength);
                }
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 解压
     */
    public static void unzip(String zipFileName, String destPath) {
        try {
            ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName));
            ZipEntry zipEntry;
            byte[] buffer = new byte[BUFFER];
            int readLength;
            while ((zipEntry = zis.getNextEntry()) != null) {
                if (zipEntry.isDirectory()) {
                    File file = new File(destPath + File.separator + zipEntry.getName());
                    if (!file.exists()) {
                        file.mkdirs();
                        continue;
                    }
                }
                File file = new File(destPath + File.separator + zipEntry.getName());
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                OutputStream os = new FileOutputStream(file);
                while ((readLength = zis.read(buffer, 0, BUFFER)) != -1) {
                    os.write(buffer, 0, readLength);
                }
                os.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}